import { DatePicker, Form, Input, InputNumber, Select, SelectProps } from 'antd';
import classNames from 'classnames';
import dayjs from 'dayjs';

import { booleanOptions } from '@/constants/config';
import { useDictStore } from '@/store/dict';

interface VariableValueFieldProps {
  value?: any;
  varType?: VariableItem['varType'];
  options?: SelectProps['options'];
  className?: string;
  onChange?: (value: any) => void;
}

export const VariableTypeSelector = memo((props: SelectProps) => {
  const { fieldTypeOptions } = useDictStore();
  const form = Form.useFormInstance();
  const onChange: SelectProps['onChange'] = (val, options) => {
    props.onChange?.(val, options);
    form?.setFieldValue?.('initValue', undefined);
  };

  return (
    <Select options={fieldTypeOptions} placeholder="请选择变量类型" className="w-full" {...(props || {})} onChange={onChange} />
  );
});

export const VariableValueField = memo<VariableValueFieldProps>((props) => {
  const { varType, options, onChange, ...rest } = props;

  const fieldProps = {
    className: classNames('w-full', props.className),
    ...rest,
    onChange(val: any) {
      onChange?.(val);
    }
  };

  if (varType === 'ENUM') {
    return (
      <Select allowClear placeholder="请选择" options={options} {...fieldProps}>
        {varType}
      </Select>
    );
  }

  if (varType === 'INTEGER') {
    return <InputNumber placeholder="请输入" precision={0} {...fieldProps} />;
  }

  if (varType === 'DECIMAL') {
    return <InputNumber placeholder="请输入" {...fieldProps} />;
  }

  if (varType === 'DATE') {
    return (
      <DatePicker
        format="YYYY/MM/DD"
        placeholder="请选择"
        {...fieldProps}
        onChange={(val) => onChange?.(val?.format('YYYY/MM/DD'))}
        value={props.value && dayjs(props.value).isValid() ? dayjs(props.value) : null}
      />
    );
  }

  if (varType === 'DATE_TIME') {
    return (
      <DatePicker
        format="YYYY/MM/DD HH:mm:ss"
        placeholder="请选择"
        {...fieldProps}
        showTime
        onChange={(val) => onChange?.(val?.format('YYYY/MM/DD HH:mm:ss'))}
        value={props.value && dayjs(props.value).isValid() ? dayjs(props.value) : null}
      />
    );
  }

  if (varType === 'BOOLEAN') {
    return <Select allowClear options={booleanOptions} {...fieldProps} placeholder="请选择" />;
  }

  return <Input placeholder="请输入" {...fieldProps} onChange={(e) => onChange?.(e.target.value)} />;
});
